package com.libui.thirdpartsdk.systemsdk

import android.content.Intent
import androidx.core.content.FileProvider
import com.libui.BaseApplication
import com.libui.thirdpartsdk.SDKInterface
import com.libui.thirdpartsdk.share.ShareCompletion
import com.libui.thirdpartsdk.share.ShareInterface
import com.libui.thirdpartsdk.share.models.ShareFileObject
import com.libui.thirdpartsdk.share.models.ShareObjectType
import com.libui.thirdpartsdk.share.models.ShareUrlObject
import java.io.File

internal class SystemShare : ShareInterface {
    companion object {
        val builder = object : ShareInterface.Builder {
            override val type: String = "system"

            override val title: String = "系统"

            override val icon: String? = null

            override val selectedIcon: String? = null

            override fun build(sdk: SDKInterface): ShareInterface {
                return SystemShare()
            }
        }
    }

    override val shareObjectTypes: List<ShareObjectType> = listOf(ShareObjectType.FILE)

    override val type: String
        get() = builder.type

    override val title: String
        get() = builder.title

    override val icon: String?
        get() = builder.icon

    override val selectedIcon: String?
        get() = builder.selectedIcon

    override var isSelected: Boolean = false

    override fun shareUrl(shareObject: ShareUrlObject, completion: ShareCompletion?) {
        val context = BaseApplication.instance

        if (context == null) {
            completion?.let { it(false) }
            return
        }

        val intent = Intent(Intent.ACTION_SEND)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.putExtra(Intent.EXTRA_SUBJECT, shareObject.title)
        intent.putExtra(Intent.EXTRA_TEXT, shareObject.url)
        intent.type = "text/plain"

        context.startActivity(
            Intent.createChooser(intent, "分享").apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) })

        completion?.let { it(true) }
    }

    override fun shareFile(shareObject: ShareFileObject, completion: ShareCompletion?) {
        val context = BaseApplication.instance
        val fileUrl = shareObject.fileUrl

        if (context == null || fileUrl == null) {
            completion?.let { it(false) }
            return
        }

        val intent = Intent(Intent.ACTION_VIEW)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        intent.setDataAndType(
            FileProvider.getUriForFile(
                context, "${context.packageName}.libui.fileprovider", File(fileUrl)
            ),
            "application/*",
        )

        context.startActivity(
            Intent.createChooser(intent, "分享").apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) })

        completion?.let { it(true) }
    }
}